'use client';

import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import { BSCToken } from '@/types/bsc';
import { apiClient } from '@/lib/api';
import { formatBNB, formatNumber, formatAddress, formatPercentage } from '@/utils/format';
import { Copy, ExternalLink, X, Twitter, Send, Globe } from 'lucide-react';
import { toast } from 'react-hot-toast';

interface TokenHolder {
  address: string;
  balance: number;
  percentage?: number;
}

interface BSCTokenDetailModalProps {
  token: BSCToken | null;
  onClose: () => void;
  onBuy?: (tokenId: string, amount: string) => void;
  onSell?: (tokenId: string, amount: string) => void;
}

const StatItem = ({
  label,
  value,
}: {
  label: string;
  value: string | number | React.ReactNode;
}) => (
  <div className="flex justify-between items-center">
    <span className="text-sm text-gray-400">{label}</span>
    <span className="text-sm font-medium text-white">{value}</span>
  </div>
);

const SocialLink = ({
  href,
  icon,
  text,
}: {
  href?: string;
  icon: React.ReactNode;
  text: string;
}) => {
  if (!href) return null;
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      className="flex items-center gap-2 text-sm text-gray-300 hover:text-purple-400 transition-colors"
    >
      {icon}
      <span>{text}</span>
    </a>
  );
};

export function BSCTokenDetailModal({ token, onClose, onBuy, onSell }: BSCTokenDetailModalProps) {
  const [tradeMode, setTradeMode] = useState<'buy' | 'sell'>('buy');
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [holders, setHolders] = useState<TokenHolder[]>([]);

  const loadHolders = useCallback(async () => {
    if (!token) return;
    try {
      setLoading(true);
      const data = await apiClient.getBSCTokenHolders(token.launchId.toString());
      const transformedHolders: TokenHolder[] = data.map((address: string) => ({
        address: address,
        balance: 0, // We don't have balance data from contributors endpoint
        percentage: 0
      }));
      setHolders(transformedHolders);
    } catch {
      console.error('Failed to load holders');
    } finally {
      setLoading(false);
    }
  }, [token]);

  useEffect(() => {
    loadHolders();
  }, [loadHolders]);

  const handleTrade = async () => {
    if (!token || !amount || parseFloat(amount) <= 0) {
      toast.error("Please enter a valid amount");
      return;
    }

    setLoading(true);
    try {
      if (tradeMode === 'buy') {
        onBuy?.(token.id, amount);
      } else {
        onSell?.(token.id, amount);
      }
      setAmount('');
      toast.success(`${tradeMode === 'buy' ? 'Purchase' : 'Sale'} successful`);
    } catch {
      toast.error(`${tradeMode === 'buy' ? 'Purchase' : 'Sale'} failed`);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success("Copied to clipboard");
  };

  if (!token) return null;

  const progress = (parseFloat(token.raisedAmount) / parseFloat(token.targetAmount)) * 100;

  return (
    <>
      {/* Overlay */}
      <div
        className={`fixed inset-0 bg-black/60 transition-opacity duration-300 z-[100] ${token ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}
        onClick={onClose}
      />

      {/* Right Drawer */}
      <div
        className={`pixel-modal fixed top-0 right-0 h-full w-[90vw] md:w-[520px] lg:w-[560px] shadow-2xl z-[110] transform transition-transform duration-300 ease-in-out ${
          token ? 'translate-x-0' : 'translate-x-full'
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Header */}
          <div className="flex justify-between items-center p-5 md:p-6 border-b border-gray-600">
            <h2 className="text-xl font-bold font-pixel">BSC</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-white transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          {/* Content */}
          <div className="flex-grow p-6 md:p-8 pt-8 md:pt-10 overflow-y-auto space-y-8">
            {/* Token Info */}
            <div className="flex items-start gap-6">
              {token.imageUrl ? (
                <Image
                  src={token.imageUrl}
                  alt={token.name}
                  width={64}
                  height={64}
                  className="rounded-full object-cover"
                />
              ) : (
                <div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-full flex items-center justify-center">
                  <span className="text-white font-bold text-2xl">
                    {token.symbol.charAt(0)}
                  </span>
                </div>
              )}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="text-2xl font-bold truncate font-body">{token.name}</h3>
                  {token.launched && (
                    <span className="inline-flex items-center px-3 py-1 text-xs font-medium bg-green-400 text-black border-2 border-black">
                      🚀 Launched
                    </span>
                  )}
                  {token.cancelled && (
                    <span className="inline-flex items-center px-3 py-1 text-xs font-medium bg-red-400 text-black border-2 border-black">
                      ❌ Cancelled
                    </span>
                  )}
                </div>
                <p className="text-sm text-gray-400 font-mono">{token.symbol}</p>
                <div className="flex items-center gap-2 mt-1">
                  <p className="text-xs text-gray-500 font-mono truncate">
                    {token.tokenAddress}
                  </p>
                  <button
                    onClick={() => copyToClipboard(token.tokenAddress)}
                    className="text-gray-400 hover:text-white"
                  >
                    <Copy size={14} />
                  </button>
                  <a
                    href={`https://bscscan.com/token/${token.tokenAddress}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-400 hover:text-white"
                  >
                    <ExternalLink size={14} />
                  </a>
                </div>
                <div className="flex items-center gap-2 mt-1">
                  <span className="text-xs text-gray-500">Creator:</span>
                  <p className="text-xs text-gray-500 font-mono truncate">
                    {formatAddress(token.creator)}
                  </p>
                  <button
                    onClick={() => copyToClipboard(token.creator)}
                    className="text-gray-400 hover:text-white"
                  >
                    <Copy size={14} />
                  </button>
                </div>
              </div>
            </div>

            {/* Stats */}
            <div className="pixel-card p-5 md:p-6 space-y-4">
              <StatItem label="Price" value={`${formatBNB(token.currentPrice)} BNB`} />
              <StatItem label="Market Cap" value={token.marketCap ? `$${formatNumber(parseFloat(token.marketCap))}` : '$0'} />
              <StatItem label="24h Volume" value={token.volume24h ? `${formatBNB(token.volume24h)} BNB` : '0 BNB'} />
              <StatItem label="Holders" value={token.holders ? formatNumber(token.holders) : '0'} />
              
              {token.priceChange24h !== undefined && token.priceChange24h !== null && (
                <StatItem 
                  label="24h Change" 
                  value={
                    <span className={token.priceChange24h >= 0 ? 'text-green-400' : 'text-red-400'}>
                      {formatPercentage(token.priceChange24h)}
                    </span>
                  } 
                />
              )}
            </div>

            {/* Progress Bar for Pre-sale */}
            {!token.launched && !token.cancelled && (
              <div className="pixel-card p-5 md:p-6">
                <div className="flex justify-between text-sm text-gray-400 mb-2">
                  <span>Funding Progress</span>
                  <span>
                    {formatBNB(token.raisedAmount)} / {formatBNB(token.targetAmount)} BNB ({progress.toFixed(1)}%)
                  </span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3">
                  <div
                    className="bg-purple-600 h-3 rounded-full transition-all duration-300"
                    style={{ width: `${Math.min(progress, 100)}%` }}
                  ></div>
                </div>
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>Start: {new Date(token.createdAt * 1000).toLocaleDateString()}</span>
                  <span>Deadline: {new Date(token.deadline * 1000).toLocaleDateString()}</span>
                </div>
              </div>
            )}

            {/* Social Links */}
            <div className="pixel-card p-5 md:p-6 space-y-4">
              <h4 className="text-md font-semibold mb-2 font-pixel">Social Links</h4>
              <div className="flex flex-wrap items-center gap-3 md:gap-4">
                <SocialLink
                  href={token.website}
                  icon={<Globe size={16} />}
                  text="Website"
                />
                <SocialLink
                  href={token.twitter}
                  icon={<Twitter size={16} />}
                  text="Twitter"
                />
                <SocialLink
                  href={token.telegram}
                  icon={<Send size={16} />}
                  text="Telegram"
                />
              </div>
            </div>

            {/* Description */}
            {token.description && (
              <div className="pixel-card p-5 md:p-6">
                <h4 className="text-md font-semibold mb-2 font-pixel">Project Description</h4>
                <p className="text-sm text-gray-300 font-body">{token.description}</p>
              </div>
            )}

            {/* Token Details */}
            <div className="pixel-card p-5 md:p-6 space-y-4">
              <h4 className="text-md font-semibold mb-2 font-pixel">Token Details</h4>
              <StatItem label="Contract Address" value={formatAddress(token.tokenAddress)} />
              <StatItem label="Creator" value={formatAddress(token.creator)} />
              <StatItem label="Created" value={new Date(token.createdAt * 1000).toLocaleDateString()} />
              <StatItem label="Total Supply" value={formatNumber(parseFloat(token.totalSupplyForSale))} />
              <StatItem label="Sold" value={formatNumber(parseFloat(token.tokensSold))} />
            </div>

            {/* Holders/Contributors */}
            {holders.length > 0 && (
              <div className="pixel-card p-5 md:p-6">
                <h4 className="text-md font-semibold mb-4 font-pixel">Contributors</h4>
                <div className="space-y-2">
                  {holders.slice(0, 10).map((holder, index) => (
                    <div key={index} className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">#{index + 1}</span>
                      <span className="text-sm font-mono text-white">{formatAddress(holder.address)}</span>
                      <span className="text-sm text-gray-300">Contributor</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="p-6 md:p-8 border-t border-gray-700 space-y-5">
            {token.launched ? (
              // Launched token info
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl">🚀</span>
                  <h4 className="text-lg font-semibold text-green-800">Token Launched</h4>
                </div>
                <p className="text-green-700 text-sm">
                  This token has been successfully launched and is now available for trading on decentralized exchanges (DEX).
                </p>
                <div className="mt-3">
                  <a
                    href={`https://pancakeswap.finance/swap?outputCurrency=${token.tokenAddress}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors"
                  >
                    Trade on PancakeSwap
                    <svg className="ml-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                    </svg>
                  </a>
                </div>
              </div>
            ) : token.cancelled ? (
              // Cancelled token info
              <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl">❌</span>
                  <h4 className="text-lg font-semibold text-red-800">Token Cancelled</h4>
                </div>
                <p className="text-red-700 text-sm">
                  This token launch has been cancelled. Investors can request refunds.
                </p>
              </div>
            ) : (
              // Active token trading interface
              <>
                <div className="flex bg-gray-800 p-2 gap-2">
                  <button
                    onClick={() => setTradeMode("buy")}
                    className={`pixel-btn flex-1 text-md font-bold transition-colors ${
                      tradeMode === "buy"
                        ? "bg-green-600 text-white"
                        : "bg-gray-600 hover:bg-gray-500"
                    }`}
                  >
                    Buy
                  </button>
                  <button
                    onClick={() => setTradeMode("sell")}
                    className={`pixel-btn flex-1 text-md font-bold transition-colors ${
                      tradeMode === "sell"
                        ? "bg-red-600 text-white"
                        : "bg-gray-600 hover:bg-gray-500"
                    }`}
                  >
                    Sell
                  </button>
                </div>

                <div className="relative mt-2">
                  <input
                    type="number"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    placeholder={`Enter ${
                      tradeMode === "buy" ? "BNB amount" : `${token.symbol} token amount`
                    }`}
                    className="pixel-input w-full"
                  />
                  <div className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-400">
                    {tradeMode === "buy" ? "BNB" : token.symbol}
                  </div>
                </div>

                <button
                  onClick={handleTrade}
                  disabled={loading || !amount || parseFloat(amount) <= 0}
                  className={`pixel-btn w-full text-lg font-bold transition-colors ${
                    tradeMode === "buy"
                      ? "bg-green-600 hover:bg-green-700"
                      : "bg-red-600 hover:bg-red-700"
                  } disabled:opacity-50 disabled:cursor-not-allowed`}
                >
                  {loading ? "Processing..." : tradeMode === "buy" ? "Buy" : "Sell"}
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}